/*
 * JSFConsole - Lightweight JSF Application Monitor
 * Copyright (C) 2009  Grzegorz Bugaj
 * http://www.gregbugaj.com
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/
package com.gregbugaj.jsfconsole.console;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
/**
 * My crazy Ajax PhaseListener responsible for dispatching methods with parameters it should handle
 * jsfdump/ajax/ajaxHandler.jsf?bean=ajaxHandler&method=methodA&p1=Item%20A&p2%20=%20Item%20B
 * jsfdump/ajax/ajaxHandler.jsf?exp=#{beanName.method}&p1=Item%20A&p2%20=%20Item%20B
 * @author devil
 *
 */
@SuppressWarnings("serial")
public class AjaxPhaseListener implements PhaseListener {
	private static final String RESOURCE_PREFIX = "/jsfconsole/ajax/";

	
	public void afterPhase(PhaseEvent event) {

	}

	
	public void beforePhase(PhaseEvent event) {		
		if(event.getPhaseId() != PhaseId.RENDER_RESPONSE){
			return;
		}

		FacesContext context=event.getFacesContext();
		ExternalContext externalContext=context.getExternalContext();
		//ServletContext servletContext = (ServletContext) externalContext.getContext(); 	
		String rootId=context.getViewRoot().getViewId();		
		//String contextRoot=context.getExternalContext().getRequestContextPath();
		Map<String, String> requestMap =context.getExternalContext().getRequestParameterMap();

		/*
		System.out.println("requestMap= "+requestMap);
		System.out.println("** PhaseEvent="+event.getPhaseId());
		System.out.println("** rootId="+rootId);
		System.out.println("** RESOURCE_PREFIX="+RESOURCE_PREFIX);
		 */

		if(!rootId.startsWith(RESOURCE_PREFIX)){
			return; 
		}
		ServletOutputStream sos = null;

		try {
			HttpServletResponse response = (HttpServletResponse)externalContext.getResponse();
			response.setCharacterEncoding("UTF-8");
			response.setStatus(HttpServletResponse.SC_OK);
			sos = response.getOutputStream();

			Class<?>[] argTypes = {ArrayList.class};
			String expression = getExpression(requestMap);
			ExpressionFactory expressionFactory=context.getApplication().getExpressionFactory();
			// create method expression
			MethodExpression methodExpression=
				expressionFactory.createMethodExpression(context.getELContext(), expression, String.class, argTypes);

			//Collect all parameters from  request param format is p1,p2,p..n
			List<String> params=new ArrayList<String>();
			int counter=1;
			while(true){
				String param=requestMap.get("p"+counter);
				if(param==null){
					break;
				}
				params.add(param);
				counter++;
			}
			// invoke method of managed bean it should return a String
			String result =(String)methodExpression.invoke(context.getELContext(), new Object[]{ params });
			sos.write(result.getBytes());

		}
		catch(javax.el.MethodNotFoundException e){
            e.printStackTrace();
			try {
				sos.write("<error>Error</error>".getBytes());
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		catch( javax.el.ELException e){
			e.printStackTrace();
            try {
				sos.write(("<error>"+e.getLocalizedMessage()+"</error>").getBytes());
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(sos!=null){
					sos.flush();
					sos.close();
				}
			} catch (IOException e) {
				//Suppressed
			}
			context.responseComplete();
		}
	}



	/**
	 * Get a expression of #{bean.method} form from request map
	 * @param requestMap
	 * @return
	 */
	private String getExpression(Map<String, String> requestMap) {
		String expression="";
		String sExp=requestMap.get("exp");
		if(isExpression(sExp)){
			expression=sExp; 
		}else{
			String method=requestMap.get("method");
			String bean=requestMap.get("bean");	
			expression="#{"+bean+"."+method+"}";
		}		
		return expression;
	}

	/**
	 * CHeck if given string is a expression from the web param ${bean.method}
	 * we use $ instead of #
	 * @param exp
	 * @return
	 */
	private boolean isExpression(String exp) {
		if(exp==null){
			return false;
		}
		return (exp.startsWith("${") && exp.endsWith("}"));
	}

	
	public PhaseId getPhaseId() {
		return PhaseId.ANY_PHASE;
	}

}
